package com.zxjbyte.yiyi.framework.common.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.zxjbyte.yiyi.framework.common.exception.ServiceException;
import lombok.experimental.UtilityClass;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.util.Set;

/**
 * 校验工具类
 * @Author zhangxingjia
 * @Date 2023/5/12 14:15
 * @Version: 1.0
 */
@UtilityClass
public class ValidationUtil {

    private Validator validator = null;
    private Validator getValidator(){
        if(validator == null){
            validator = SpringUtil.getBean(Validator.class);
        }
        return validator;
    }

    public void validate(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = getValidator().validate(object, groups);
        if (CollUtil.isNotEmpty(constraintViolations)) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }

    public void checkNotNull(Object arg, String errorMsg, Object... params) {
        if (arg == null) {
            throw new ServiceException(StrUtil.format(errorMsg, params));
        }
    }

    public void checkNotNull(Object arg, String argName) {
        if (arg == null) {
            throw new ServiceException(argName + " must not be null.");
        }
    }

    public void checkNotEmptyAsString(String arg, String argName) {
        checkNotNull(arg, argName);
        if (arg.isEmpty()) {
            throw new ServiceException(argName + " must be a non-empty string.");
        }
    }

    public void checkNotBlankAsString(String arg, String argName) {
        checkNotNull(arg, argName);
        if (StrUtil.isBlank(arg)) {
            throw new ServiceException(argName + " must be a non-empty string.");
        }
    }

    public void checkNullOrPositive(Number arg, String argName) {
        if (arg != null && arg.longValue() < 0) {
            throw new ServiceException(argName + " cannot be non-negative.");
        }
    }
}
